hdu1242 参考答案

返回“大学生程序设计竞赛”

/*
zju 1649 ,hdu 1242 最短路径 BFS
ymc 2008/9/17
题目大意:
在一个n×m的地图上,天使用a表示,天使的一些朋友用r表示。#表示墙,.表示路。
x表示有一个守卫。r可以上下左右移动,每次只能移动一个点,需要1的时间。如果移到
x的位置,需要额外1的时间杀掉x。
求从r到a的最小时间
解题思路:
求所有r到其它点的的最短距离。
dist[i][j]记录所有r到点i,j的最短距离,所有r的dist为0.
used标记点i,j的最短距离是否已经求出。用BFS搜索a的距离。

*/
#include <iostream>
#include <queue>
using namespace std;
const int N=300;
int dist[N][N];
char graph[N][N];
int step[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
struct Pt
{
    int x,y;
    int d;
    Pt(int xx=0,int yy=0,int dd=-1)
    {
        x=xx;y=yy;d=dd;
    }
    bool operator<(const Pt &p)const
    {
        return d>p.d;
    }
};
int n,m;
int ax,ay;
void BFS()
{

    priority_queue<Pt> q;
    for(int i=0;i<n;i++)
        for(int j=0;j<m;j++)
        {
            dist[i][j]=-1;
            if(graph[i][j]=='a')
            {
                ax=i;ay=j;
            }
            else if(graph[i][j]=='r')
            {
                q.push(Pt(i,j,0));
                dist[i][j]=0;
            }
        }
    Pt u;
    int x1,y1;
    while(!q.empty())
    {
        u=q.top();
        q.pop();
        if(u.x==ax && u.y== ay)
            return ;
        for(int k=0;k<4;k++)
        {
            x1=u.x+step[k][0];
            y1=u.y+step[k][1];
            if(x1<0||x1>=n||y1<0||y1>=m)
                continue;
            if(dist[x1][y1]>=0||graph[x1][y1]=='#')
                continue;
            if(graph[x1][y1]=='x')
                dist[x1][y1]=dist[u.x][u.y]+2;
            else
                dist[x1][y1]=dist[u.x][u.y]+1;
            q.push(Pt(x1,y1,dist[x1][y1]));
        }
    }
}
int main()
{
    while(cin>>n>>m)
    {
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                cin>>graph[i][j];
        BFS();
        if(dist[ax][ay]>=0)
            cout<<dist[ax][ay]<<endl;
        else
            cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
    }
}